package com.cgtong.android.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.location.LocationManager;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapDoubleClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapLongClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapTouchListener;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cgtong.android.R;
import com.cgtong.android.base.BaseTitleActivity;
import com.cgtong.android.http.ConstantManager;
import com.cgtong.android.service.LocationService;
import com.cgtong.android.util.FileUtils;
import com.cgtong.android.util.PostUtil;
import com.cgtong.android.widget.BaseDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 所在位置地图显示
 */
public class BDLocationMapActivity extends BaseTitleActivity implements OnGetGeoCoderResultListener {

    public static final String EXTRA_LOCATION_ADDRESS = "location_address";  //定位地址
    public static final String EXTRA_LOCATION_LATITUDE = "location_latitude"; //定位纬度
    public static final String EXTRA_LOCATION_LONGITUDE = "location_longitude"; //定位经度
    public static final String EXTRA_LOCATION_SNAPIMAGE_PATH = "location_snapimage_path"; //定位的截图路径

    // 定位相关
    GeoCoder mSearch = null;
    private LocationListener myListener = new LocationListener();
    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private String mCurrentAddress;
    private String mCurrentSnapImagePath;
    private boolean isBackResult = false;
    private boolean isGeoSearching = false;
    private boolean isMapRenderSuccess = false;
    private String mCurrentAddStr;
    private String locationAddress;

    @BindView(R.id.bmapView)
    MapView mMapView;
    @BindView(R.id.tv_mylocation)
    EditText mTvLocation;
    //    @BindView(R.id.tv_reset_location)
//    TextView mTvResetLocation;
    @BindView(R.id.auto_location_fl)
    FrameLayout mAutoLocationFL;
    //    @BindView(R.id.location_progress)
//    ImageView mIvLocationProgress;
    @BindView(R.id.location_txt)
    TextView mAutoLocationTxt;
    @BindView(R.id.pg_start_location)
    ProgressBar mPgStartLocation;
    @BindView(R.id.btn_confirm_location)
    Button mConfirmBtn;

    private Double lastX = 0.0;
    private int mCurrentDirection = 0;
    private float mCurrentAccracy;
    private boolean isFirstLoc = true, isReseting = false;
    private BaiduMap mBaiduMap;
    private MyLocationData locData;
    private ProgressDialog progressDialog;
    private LocationService mLocationService;
    private UiSettings mUiSettings;
    BitmapDescriptor bdA = BitmapDescriptorFactory
            .fromResource(R.drawable.icon_marka);

    int curIndex = 0;
    int before_length;

    private final int SHOW_PROGRESS_MSG = 0x01;
    private final int UPDATE_PROGRESS_MSG = 0x02;
    private final int EXIT_PROGRESS_MSG = 0x03;
    private ProgressHandlerThread mProgressHandlerThread;

    private LocationManager mLocationManager;
    private SubmitCallback mSubmitCallback;
    private final int GPS_REQUEST_CODE = 0x02;

    /**
     * 启动Activity，在上一级页面实现onActivityResult方法，获取对应的地图、位置等参数
     *
     * @param context   上下文
     * @param latitude  纬度
     * @param longitude 经度
     * @param address   地址
     */
    public static void actionStart(Activity context, double latitude, double longitude, String address) {
        Intent intent = new Intent(context, BDLocationMapActivity.class);
        intent.putExtra(EXTRA_LOCATION_LATITUDE, String.valueOf(latitude));
        intent.putExtra(EXTRA_LOCATION_LONGITUDE, String.valueOf(longitude));
        intent.putExtra(EXTRA_LOCATION_ADDRESS, address);
        context.startActivityForResult(intent, ConstantManager.REQUEST_MAP_CODE);
    }

    /**
     * 启动Activity，在上一级页面实现onActivityResult方法，获取对应的地图、位置等参数
     *
     * @param context 上下文
     * @param address 地址
     */
    public static void actionStart(Activity context, String address) {
        Intent intent = new Intent(context, BDLocationMapActivity.class);
        intent.putExtra(EXTRA_LOCATION_ADDRESS, address);
        context.startActivityForResult(intent, ConstantManager.REQUEST_MAP_CODE);
    }

    @Override
    protected String getContentTitle() {
        return getResources().getString(R.string.txt_title_location);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_location;
    }

    private void setMapViewAlpha(int alpha) {
        if (null != mMapView) {
            mMapView.setAlpha(alpha);
            if (alpha == 255 && null != mUiSettings) {
                //mUiSettings.setScrollGesturesEnabled(true);
            }
        }
    }

    private boolean isMapViewNoTransparent() {
        return mMapView.getAlpha() == 255;
    }

    @Override
    protected void loadDataByNet() {
        mProgressHandlerThread = new ProgressHandlerThread("progress-handler-thread");
        mProgressHandlerThread.start();
        //地图初始化
        //setMapViewAlpha(0);
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mBaiduMap = mMapView.getMap();
        mMapView.showScaleControl(false);
        mMapView.showZoomControls(false);
        mUiSettings = mBaiduMap.getUiSettings();
        mUiSettings.setZoomGesturesEnabled(false);
        mUiSettings.setScrollGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setCompassEnabled(false);
        mBaiduMap.setMyLocationEnabled(true);
        setMapViewAlpha(255);
        //mBaiduMap.getUiSettings().setAllGesturesEnabled(false);
        //mBaiduMap.setMyLocationEnabled(true);

        // 定位初始化
        isFirstLoc = true;
        mLocationService = new LocationService(this);
        mLocationService.registerListener(myListener);
        mLocationService.setLocationOption(mLocationService.getDefaultLocationClientOption());
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);

        Intent intent = getIntent();
        locationAddress = intent.getStringExtra(EXTRA_LOCATION_ADDRESS);
        double lon = Double.valueOf(intent.getStringExtra(EXTRA_LOCATION_LONGITUDE));
        double lat = Double.valueOf(intent.getStringExtra(EXTRA_LOCATION_LATITUDE));
        if (lon > 0 && lat > 0) {
            setMapViewAlpha(255);
            updateMapState(new LatLng(lat, lon));
        } else {
            if (!TextUtils.isEmpty(locationAddress)) {
                mTvLocation.setText(locationAddress);
                isGeoSearching = true;
                isReseting = false;
                setMapViewAlpha(255);
                mSubmitCallback = null;
                mSearch.geocode(new GeoCodeOption().city("").address(locationAddress));
            } else {
                /*mIvLocationProgress.setVisibility(View.GONE);
                mPgStartLocation.setVisibility(View.VISIBLE);
                isReseting = true;
                isGeoSearching = true;
                mTvResetLocation.setEnabled(false);
                mLocationService.start();*/
            }
        }
        mTvLocation.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                before_length = s.length();
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                curIndex = start;
            }

            @Override
            public void afterTextChanged(Editable s) {
                int after_length = s.length();
                if (after_length > 50) {
                    int diff_value = after_length - 50;
                    int diff_num = after_length - before_length;
                    int startCur = curIndex + (diff_num - diff_value);
                    int endCur = curIndex + diff_num;
                    Editable text_new = s.delete(startCur, endCur);
                    mTvLocation.setText(text_new.toString());
                    mTvLocation.setSelection(startCur);
                    ToastUtils.showShort(getString(R.string.txt_location_beyond));
                }
            }
        });
        initListener();
        PostUtil.postSuccessDelayed(loadService);
    }

    @Override
    protected void onDataReloadByNet(View v) {
    }

    /**
     * 对地图事件的消息响应
     */
    private void initListener() {
        mBaiduMap.setOnMapTouchListener(new OnMapTouchListener() {
            @Override
            public void onTouch(MotionEvent event) {
            }
        });

        mBaiduMap.setOnMapClickListener(new OnMapClickListener() {
            /**
             * 单击地图
             */
            public void onMapClick(LatLng point) {
                /*if (isMapViewNoTransparent()) {
                    updateMapState(point);
                }*/
            }

            /**
             * 单击地图中的POI点
             */
            public boolean onMapPoiClick(MapPoi poi) {
                /*if (isMapViewNoTransparent()) {
                    updateMapState(poi.getPosition());
                }*/
                return false;
            }
        });
        mBaiduMap.setOnMapLongClickListener(new OnMapLongClickListener() {
            /**
             * 长按地图
             */
            public void onMapLongClick(LatLng point) {
                /*if (isMapViewNoTransparent()) {
                    updateMapState(point);
                }*/
            }
        });
        mBaiduMap.setOnMapDoubleClickListener(new OnMapDoubleClickListener() {
            /**
             * 双击地图
             */
            public void onMapDoubleClick(LatLng point) {
                /*if (isMapViewNoTransparent()) {
                    updateMapState(point);
                }*/
            }
        });
    }

    /**
     * 更新地图状态显示位置
     */
    private void updateMapState(LatLng point) {
        if (mSearch == null || point == null) {
            return;
        }
//        mIvLocationProgress.setVisibility(View.GONE);
        mAutoLocationTxt.setVisibility(View.GONE);
        mPgStartLocation.setVisibility(View.VISIBLE);
//        mTvResetLocation.setEnabled(false);
        mAutoLocationFL.setEnabled(false);
        mConfirmBtn.setEnabled(false);
        mLocationService.stop();
        isGeoSearching = true;
        isReseting = false;
        mSearch.reverseGeoCode(new ReverseGeoCodeOption()
                .location(point).newVersion(1));
    }

    /**
     * 定位SDK监听函数
     */
    public class LocationListener extends BDAbstractLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location == null || mMapView == null) {
                return;
            }
            mCurrentLat = location.getLatitude();
            mCurrentLon = location.getLongitude();
            StringBuffer address = new StringBuffer(200);
            if (!TextUtils.isEmpty(location.getCity()) && !"null".equals(location.getCity())) {
                address.append(location.getCity());
            }
            if (!TextUtils.isEmpty(location.getDistrict()) && !"null".equals(location.getDistrict())) {
                address.append(location.getDistrict());
            }
            if (!TextUtils.isEmpty(location.getStreet()) && !"null".equals(location.getStreet())) {
                address.append(location.getStreet());
            }
            if (!TextUtils.isEmpty(location.getStreetNumber()) && !"null".equals(location.getStreetNumber())) {
                address.append(location.getStreetNumber());
            }
            if (!TextUtils.isEmpty(address.toString())) {
                mCurrentAddress = mCurrentAddStr = address.toString();
                mTvLocation.setText(mCurrentAddress);
            } else {
                mTvLocation.setText(getResources().getString(R.string.title_location_error));
            }
            isReseting = false;
//            mIvLocationProgress.setVisibility(View.VISIBLE);
            mAutoLocationTxt.setVisibility(View.VISIBLE);

            mPgStartLocation.setVisibility(View.GONE);
//            mTvResetLocation.setEnabled(true);
            mAutoLocationFL.setEnabled(true);
            LogUtils.i("BD_MAP", "request location success" + isFirstLoc);
            if (isFirstLoc) {
                isFirstLoc = false;
                locData = new MyLocationData.Builder()
                        .accuracy(0)
                        .direction(0).latitude(location.getLatitude())
                        .longitude(location.getLongitude()).build();
                mBaiduMap.setMyLocationData(locData);
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                if (!isReseting) {
                    mBaiduMap.clear();
                    mBaiduMap.addOverlay(new MarkerOptions().position(ll)
                            .icon(bdA));
                    MapStatus.Builder builder = new MapStatus.Builder();
                    builder.target(ll).zoom(18.0f);
                    mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                }
                if (!isReseting)
                    OnMapRenderCallback(ll);
            }
            mLocationService.stop();
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @OnClick(R.id.auto_location_fl)
    public void resetLocation() {
        //权限、GPS判断
        doLocationByPermission();
    }

    @OnClick(R.id.btn_confirm_location)
    public void confirmLocation() {
        mCurrentAddress = mTvLocation.getText().toString();
        if (TextUtils.isEmpty(mCurrentAddress)) {
            ToastUtils.showShort("地址不能为空");
            return;
        }
        showCommitAddressDialog();
    }

    /**
     * 提交地址显示弹窗
     */
    private void showCommitAddressDialog() {
        BaseDialog.create(getSupportFragmentManager())
                .setLayoutRes(R.layout.layout_commit_address)
                .setViewListener(new BaseDialog.ViewListener() {

                    @Override
                    public void bindView(View view, final Dialog dialog) {
                        TextView yourAddressTxt = (TextView) view.findViewById(R.id.your_address_txt);
                        yourAddressTxt.setText(mCurrentAddress);
                        view.findViewById(R.id.confirm_btn).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (isReseting) {
                                    return;
                                }
                                KeyboardUtils.hideSoftInput(mTvLocation);
                                isReseting = false;
                                if (isUpdateAddressInfo()) {
                                    LogUtils.i("BD_MAP", "is update address info");
//                mIvLocationProgress.setVisibility(View.GONE);
                                    mAutoLocationTxt.setVisibility(View.GONE);
                                    mPgStartLocation.setVisibility(View.VISIBLE);
                                    setMapViewAlpha(255);
//                mTvResetLocation.setEnabled(false);
                                    mAutoLocationFL.setEnabled(false);
                                    mConfirmBtn.setEnabled(false);
                                    isGeoSearching = true;
                                    mSubmitCallback = new SubmitCallback(){
                                        @Override
                                        public void onSubmitOk(){
                                            backPrevActivity();
                                            mSubmitCallback = null;
                                        }
                                    };
                                    mSearch.geocode(new GeoCodeOption().city("").address(mCurrentAddress));
                                } else {
                                    backPrevActivity();
//                                    ToastUtils.showShort("已定位成功");
                                }
                                dialog.cancel();
                            }
                        });
                        view.findViewById(R.id.cancel_btn).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.cancel();
                            }
                        });


                    }
                }).setDimAmount(0.3f)
                .setStyle(R.style.DefaultCenterDialog)
                .setCanCancelable(false).
                setGravity(Gravity.CENTER)
                .show();
    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {
//        mIvLocationProgress.setVisibility(View.VISIBLE);
        mAutoLocationTxt.setVisibility(View.VISIBLE);

        mPgStartLocation.setVisibility(View.GONE);
//        mTvResetLocation.setEnabled(true);
        mAutoLocationFL.setEnabled(true);
        mConfirmBtn.setEnabled(true);
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            ToastUtils.showShort("抱歉，未能找到结果");
            isGeoSearching = false;
            return;
        }
        mCurrentLat = result.getLocation().latitude;
        mCurrentLon = result.getLocation().longitude;
        mCurrentAddress = mCurrentAddStr = mTvLocation.getText().toString();

        mBaiduMap.clear();
        mBaiduMap.addOverlay(new MarkerOptions().position(result.getLocation())
                .icon(bdA));
        final LatLng point = new LatLng(mCurrentLat, mCurrentLon);
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(point).zoom(18.0f);
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        //OnMapRenderCallback(point);
        if (!isReseting && !isBackResult) {
            mBaiduMap.setOnMapRenderCallbadk(new BaiduMap.OnMapRenderCallback() {
                @Override
                public void onMapRenderFinished() {
                    if (!isReseting && !isBackResult) {
                        isMapRenderSuccess = true;
                        if(null!=mSubmitCallback){
                            mSubmitCallback.onSubmitOk();
                        }
                    }
                }
            });
        }
    }

    private void OnMapRenderCallback(final LatLng ll) {
        if (!isReseting && !isBackResult) {
            mBaiduMap.setOnMapRenderCallbadk(new BaiduMap.OnMapRenderCallback() {
                @Override
                public void onMapRenderFinished() {
                    if (!isReseting && !isBackResult) {
                        LogUtils.i("BD_MAP", "onMapRenderFinished" + ll.longitude + ";;" + ll.latitude);
                        isMapRenderSuccess = true;
                    }
                }
            });
        }
    }

    private boolean isUpdateAddressInfo() {
        return !(mCurrentLat > 0 && mCurrentLon > 0
                && !TextUtils.isEmpty(mCurrentAddress) && !TextUtils.isEmpty(mCurrentAddStr) && mCurrentAddStr.equals(mCurrentAddress));
    }

    class ProgressHandlerThread extends HandlerThread {
        private ProgressDialog progressDialog;
        private Handler progressHandler;

        public ProgressHandlerThread(String name) {
            super(name);
        }

        @Override
        protected void onLooperPrepared() {
            super.onLooperPrepared();
            progressDialog = new ProgressDialog(BDLocationMapActivity.this);
            progressDialog.setMessage("位置信息保存中...");
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progressDialog.setIndeterminate(false);
            progressHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case SHOW_PROGRESS_MSG:
                            if (null != progressDialog) {
                                progressDialog.show();
                            }
                            break;
                        case UPDATE_PROGRESS_MSG:
                            if (null != progressDialog) {
                                progressDialog.setMessage((String) msg.obj);
                            }
                            break;
                        case EXIT_PROGRESS_MSG:
                            if (null != progressDialog && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            break;
                        default:
                            break;
                    }
                }
            };
        }

        public void sendMessage(int what, Object obj) {
            if (obj == null) {
                progressHandler.sendEmptyMessage(what);
            } else {
                Message msg = progressHandler.obtainMessage();
                msg.what = what;
                msg.obj = obj;
                progressHandler.sendMessage(msg);
            }
        }

        @Override
        public boolean quit() {
            progressHandler.removeCallbacksAndMessages(null);
            return super.quit();
        }
    }

    private void setBackResult() {
        isBackResult = false;
        mProgressHandlerThread.sendMessage(EXIT_PROGRESS_MSG, null);
        Intent intent = getIntent();
        if (!TextUtils.isEmpty(mCurrentAddress)) {
            intent.putExtra(EXTRA_LOCATION_ADDRESS, mCurrentAddress);
        }
        intent.putExtra(EXTRA_LOCATION_LATITUDE, mCurrentLat);
        intent.putExtra(EXTRA_LOCATION_LONGITUDE, mCurrentLon);
        if (!TextUtils.isEmpty(mCurrentSnapImagePath)) {
            intent.putExtra(EXTRA_LOCATION_SNAPIMAGE_PATH, mCurrentSnapImagePath);
        }
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void backClick() {
        KeyboardUtils.hideSoftInput(mTvLocation);
        super.backClick();
    }

    protected void backPrevActivity() {
        KeyboardUtils.hideSoftInput(mTvLocation);
        mCurrentAddress = mTvLocation.getText().toString();
        if (TextUtils.isEmpty(mCurrentAddress) || mCurrentAddress.equals(getResources().getString(R.string.title_location_error))) {
            setResult(RESULT_CANCELED);
            super.backClick();
            return;
        }

        if (isGeoSearching) {
            isBackResult = true;
            mProgressHandlerThread.sendMessage(SHOW_PROGRESS_MSG, null);
            if (isMapRenderSuccess) {
                doSnapShotMapView();
            } else {
                doSnapShotMapViewOnReaderFinished();
            }
        } else {
            isBackResult = false;
            setBackResult();
        }
    }

    private void doSnapShotMapViewOnReaderFinished() {
        mBaiduMap.setOnMapRenderCallbadk(new BaiduMap.OnMapRenderCallback() {
            @Override
            public void onMapRenderFinished() {
                doSnapShotMapView();
            }
        });
    }

    private void doSnapShotMapView() {
        mBaiduMap.snapshot(new BaiduMap.SnapshotReadyCallback() {
            @Override
            public void onSnapshotReady(Bitmap bitmap) {
                if (!isReseting && FileUtils.isSDCardAvailable()) {
                    File file = new File(getExternalCacheDir().getAbsolutePath() + "/map_view_" + mCurrentLon + "_" + mCurrentLat + ".png");
                    boolean b = ImageUtils.save(bitmap, file, Bitmap.CompressFormat.PNG);
                    LogUtils.d("--------------保存快照--------------" + b);
                    LogUtils.i("BD_MAP", "onSnapshotReady success");
                    mCurrentSnapImagePath = file.getAbsolutePath();
                    mBaiduMap.setOnMapRenderCallbadk(null);
                    if (isBackResult) {
                        setBackResult();
                    }
                    isGeoSearching = false;
                }
            }
        });
    }

    @Override
    public void onBackPressed() {
        this.backClick();
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
//        mIvLocationProgress.setVisibility(View.VISIBLE);
        mAutoLocationTxt.setVisibility(View.VISIBLE);

        mPgStartLocation.setVisibility(View.GONE);
//        mTvResetLocation.setEnabled(true);
        mAutoLocationFL.setEnabled(true);
        mConfirmBtn.setEnabled(true);
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            ToastUtils.showShort("抱歉，未能找到结果");
            isGeoSearching = false;
            return;
        }
        ReverseGeoCodeResult.AddressComponent addressComponent = result.getAddressDetail();
        LatLng latlng = result.getLocation();
        mCurrentLat = latlng.latitude;
        mCurrentLon = latlng.longitude;
        StringBuffer address = new StringBuffer(200);
        String city = addressComponent.city;
        String district = addressComponent.district;
        String street = addressComponent.street;
        String streetNumber = addressComponent.streetNumber;
        if (!TextUtils.isEmpty(city) && !"null".equals(city)) {
            address.append(city);
        }
        if (!TextUtils.isEmpty(district) && !"null".equals(district)) {
            address.append(district);
        }
        if (!TextUtils.isEmpty(street) && !"null".equals(street)) {
            address.append(street);
        }
        if (!TextUtils.isEmpty(streetNumber) && !"null".equals(streetNumber)) {
            address.append(streetNumber);
        }
        String addressStr = address.toString();
        if (TextUtils.isEmpty(addressStr)) {
            addressStr = result.getAddress();
        }
        mCurrentAddress = mCurrentAddStr = addressStr;
        mTvLocation.setText(addressStr);

        LatLng point = new LatLng(mCurrentLat, mCurrentLon);
        mBaiduMap.clear();
        mBaiduMap.addOverlay(new MarkerOptions().position(point).icon(bdA));
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(point).zoom(18.0f);
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
        //mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));
        isReseting = false;
        OnMapRenderCallback(point);
        /*mBaiduMap.clear();
        mBaiduMap.addOverlay(new MarkerOptions().position(latlng)
                .icon(bdA));
        mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(latlng));
        mBaiduMap.snapshot(new BaiduMap.SnapshotReadyCallback() {
                            @Override
                            public void onSnapshotReady(Bitmap bitmap) {
                                Log.i("BD_MAP", "getReverseGeo onSnapshotReady");
                                if (!isReseting && FileUtils.isSDCardAvailable()) {
                                    File file = new File(getExternalCacheDir().getAbsolutePath() + "/map_view_" + mCurrentLon + "_" + mCurrentLat + ".png");
                                    boolean b = ImageUtils.save(bitmap, file, Bitmap.CompressFormat.PNG);
                                    LogUtils.d("--------------保存快照--------------"+b);
                                    mCurrentSnapImagePath = file.getAbsolutePath();
                                    if (isBackResult){ setBackResult(); }
                                    isGeoSearching = false;
                                }
                            }
                        });*/
        //Toast.makeText(this, result.getAddress(),Toast.LENGTH_LONG).show();
    }

    @Override
    protected void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    protected void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // 退出时销毁定位
        if (null != mLocationService) {
            mLocationService.unregisterListener(myListener); //注销掉监听
            mLocationService.stop(); //停止定位服务
        }
        if (null != mProgressHandlerThread)
            mProgressHandlerThread.quit();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mSearch.destroy();
        mMapView = null;
        super.onDestroy();
    }

    private void refreshLocation() {
        isFirstLoc = true;
        isGeoSearching = true;
        isReseting = true;
        setMapViewAlpha(255);
//        mIvLocationProgress.setVisibility(View.GONE);
        mAutoLocationTxt.setVisibility(View.GONE);

        mPgStartLocation.setVisibility(View.VISIBLE);
//        mTvResetLocation.setEnabled(false);
        mAutoLocationFL.setEnabled(false);
        LogUtils.i("BD_MAP", "reset request location");
        mLocationService.requestLocation();
    }

    private void initGPS() {
        //判断GPS模块是否开启，如果没有则开启
        if (!mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            final AlertDialog.Builder dialog = new AlertDialog.Builder(BDLocationMapActivity.this);
            dialog.setTitle("提示");
            dialog.setMessage("为了定位更加准确，请先打开GPS");
            dialog.setPositiveButton("设置", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    // 转到手机设置界面，用户设置GPS
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivityForResult(intent, GPS_REQUEST_CODE); // 设置完成后返回到原来的界面
                }
            });
            dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                    ToastUtils.showShort("GPS未打开，将使用网络进行定位");
                    refreshLocation();
                }
            });
            dialog.show();
        } else {
            refreshLocation();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GPS_REQUEST_CODE) {
            if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                refreshLocation();
            } else {
                ToastUtils.showShort("GPS未打开，将使用网络进行定位");
                refreshLocation();
            }
        }
    }

    private void doLocationByPermission() {
        if (Build.VERSION.SDK_INT >= 23) {
            RxPermissions rxPermissions = new RxPermissions(BDLocationMapActivity.this);
            rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION)
                    .subscribe(new Observer<Boolean>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onNext(Boolean aBoolean) {
                            if (aBoolean) {
                                initGPS();
                            } else {
                                ToastUtils.showLong(R.string.permission_request_denied);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onComplete() {
                        }
                    });
        } else {
            initGPS();
        }
    }

    public interface SubmitCallback{
        public void onSubmitOk();
    }
}